package com.xjrsoft.common.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.hutool.core.util.ObjectUtil;
import com.xjrsoft.common.enums.ErrorTypeEnum;
import com.xjrsoft.common.enums.ResponseCode;
import com.xjrsoft.common.model.result.R;
import com.xjrsoft.config.CommonPropertiesConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.naming.NoPermissionException;
import java.util.List;

/**
 * @Author: tzx
 * @Date: 2022/3/3 15:38
 */
@RestControllerAdvice
@Slf4j
@RequiredArgsConstructor
public class GlobalExceptionHandler {

    private final CommonPropertiesConfig commonPropertiesConfig;

    private final String ERROR_MESSAGE = "系统错误，请联系管理员！";

    private final String NOTLOGIN_MESSAGE = "系统未登录，请登录！";

    /**
     * 全局异常处理
     *
     * @Author: tzx
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R globalExceptionHandler(Exception e){
        log.error(e.getMessage(), e);
        if (commonPropertiesConfig.getErrorType() == ErrorTypeEnum.SYSTEM) {
            return R.error(ResponseCode.INTERNAL_SERVER_ERROR.getCode(),e.getMessage());
        }
        else{
            return R.error(ResponseCode.INTERNAL_SERVER_ERROR.getCode(),ERROR_MESSAGE);
        }
    }

    /**
     * 自定义异常处理抛出错误，可以指定code
     *
     * @Author: tzx
     */
    @ExceptionHandler(MyException.class)
    @ResponseBody
    public R globalMyExceptionHandler(MyException e){
        log.error(e.getMessage(), e);
        if (ObjectUtil.isNotNull(e.getCode())){
            return R.error(e.getCode(),e.getMessage());
        }else {
            return R.error(ResponseCode.INTERNAL_SERVER_ERROR.getCode(),e.getMessage());
        }
    }

    /**
     * 未登录异常处理
     *
     * @Author: tzx
     */
    @ExceptionHandler(NotLoginException.class)
    @ResponseBody
    public R notLoginExceptionHandler(NotLoginException e){
        log.error(e.getMessage(), e);
        if (commonPropertiesConfig.getErrorType() == ErrorTypeEnum.SYSTEM) {
            return R.error(ResponseCode.UN_AUTHORIZED.getCode(),ResponseCode.UN_AUTHORIZED.getMessage());
        }
        else{
            return R.error(ResponseCode.UN_AUTHORIZED.getCode(),NOTLOGIN_MESSAGE);
        }

    }

    /**
     * 权限异常
     *
     * @Author: tzx
     */
    @ExceptionHandler(NotPermissionException.class)
    @ResponseBody
    public R notPermissionExceptionHandler(NotPermissionException e){
        log.error(e.getMessage(), e);
        if (commonPropertiesConfig.getErrorType() == ErrorTypeEnum.SYSTEM) {
            return R.error(ResponseCode.UN_AUTHORIZED.getCode(),e.getMessage());
        }
        else{
            return R.error(ResponseCode.UN_AUTHORIZED.getCode(),ERROR_MESSAGE);
        }
    }

    /**
     * 参数错误异常
     *
     * @Author: tzx
     */
    @ResponseBody
    @ExceptionHandler({BindException.class})
    public R paramExceptionHandler(BindException e) {
        log.error(e.getMessage(), e);
        BindingResult exceptions = e.getBindingResult();
        // 判断异常中是否有错误信息，如果存在就使用异常中的消息，否则使用默认消息
        if (exceptions.hasErrors()) {
            List<ObjectError> errors = exceptions.getAllErrors();
            if (!errors.isEmpty()) {
                // 这里列出了全部错误参数，按正常逻辑，只需要第一条错误即可
                FieldError fieldError = (FieldError) errors.get(0);
                return R.error(fieldError.getDefaultMessage());
            }
        }
        return R.error("请求参数错误");
    }

}
